package com.platform.user.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.platform.bean.JsonResult;
import com.platform.bean.PageInfo;
import com.platform.exception.BaseException;
import com.platform.user.dao.LostHelpNoticeDao;
import com.platform.user.entity.Announcement;
import com.platform.user.entity.LostHelpNotice;
import com.platform.utils.BaiduSimilarImageServerUtils;
import com.platform.utils.Base64Utils;
import com.platform.utils.PrintMessageUtils;
import com.platform.utils.UploadFileToRemoteUtils;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LostHelpNoticeService {

    @Resource
    private LostHelpNoticeDao lostHelpNoticeDao;

    public void redisplayLostHelpNotice(Map<String, Object> params) throws IOException, JSONException {
        Integer id = Integer.parseInt(params.get("itemId").toString());
        LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(id);
        if (lostHelpNotice != null) {
            lostHelpNotice.setIfViolation(0);
            String imageUrlToBase64 = Base64Utils.convertImageUrlToBase64(lostHelpNotice.getImageCover());
            Map<String, Object> baiduImageReq = new HashMap<>();
            baiduImageReq.put("brief", lostHelpNotice.getId());
            if (lostHelpNotice.getItemStatus() == 1 || lostHelpNotice.getItemStatus() == 2) {
                baiduImageReq.put("classId1", "1");
            } else if (lostHelpNotice.getItemStatus() == 3) {
                baiduImageReq.put("classId1", "2");
            }
            baiduImageReq.put("image", imageUrlToBase64);
            int i = BaiduSimilarImageServerUtils.updateImage(baiduImageReq);
            if (i != 1) {
                System.out.println("百度云更新失败");
                return;
            }
            lostHelpNoticeDao.update(lostHelpNotice);
        }
    }

    public void illegalWithdrawalLostHelpNotice(Map<String, Object> params) throws IOException, JSONException {
        Integer id = Integer.parseInt(params.get("itemId").toString());
        LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(id);
        if (lostHelpNotice != null) {
            lostHelpNotice.setIfViolation(1);
            String imageUrlToBase64 = Base64Utils.convertImageUrlToBase64(lostHelpNotice.getImageCover());
            Map<String, Object> baiduImageReq = new HashMap<>();
            baiduImageReq.put("brief", lostHelpNotice.getId());
            baiduImageReq.put("classId1", "3");
            //baiduImageReq.put("classId2", "3");
            baiduImageReq.put("image", imageUrlToBase64);
            int i = BaiduSimilarImageServerUtils.updateImage(baiduImageReq);
            if (i != 1) {
                System.out.println("百度云更新失败");
                return;
            }
            lostHelpNoticeDao.update(lostHelpNotice);
        }
    }

    public void setItemHadFound(Map<String, Object> params) throws IOException, JSONException {
        Integer id = Integer.parseInt(params.get("itemId").toString());
        LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(id);
        if (lostHelpNotice != null) {
            lostHelpNotice.setItemStatus(3);
            String imageUrlToBase64 = Base64Utils.convertImageUrlToBase64(lostHelpNotice.getImageCover());
            Map<String, Object> baiduImageReq = new HashMap<>();
            baiduImageReq.put("brief", lostHelpNotice.getId());
            baiduImageReq.put("classId1", "2");
            baiduImageReq.put("image", imageUrlToBase64);
            int i = BaiduSimilarImageServerUtils.updateImage(baiduImageReq);
            if (i == -1) {
                System.out.println("百度云更新失败");
                return;
            }
            lostHelpNoticeDao.update(lostHelpNotice);
        }
    }

    public void deleteByItemId(Map<String, Object> params) {
        lostHelpNoticeDao.deleteById(Integer.parseInt(params.get("itemId").toString()));
    }

    public LostHelpNotice queryOneLostHelpNoticeByItemId(Map<String, Object> params) {
        return lostHelpNoticeDao.queryById(Integer.parseInt(params.get("id").toString()));
    }

    public LostHelpNotice queryOneLostHelpNoticeByItemId(Integer itemId) {
        return lostHelpNoticeDao.queryById(itemId);
    }

    public PageInfo<LostHelpNotice> queryLostHelpNoticeByPage(Map<String, Object> params) {
        //params.put("ifViolation", 0);
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);
        PrintMessageUtils.traverseMap(params);
        params.putIfAbsent("itemStatus", "");

        // PrintMessageUtils.traverseList(lostHelpNoticeList);
        String lostPositionCoordinate = (String) params.get("lostPositionCoordinate");
        if (lostPositionCoordinate != null && !lostPositionCoordinate.isEmpty()) {
            String[] coordinates = lostPositionCoordinate.split(",");
            if (coordinates.length == 2) {
                params.put("longitude", Double.parseDouble(coordinates[0].trim()));
                params.put("latitude", Double.parseDouble(coordinates[1].trim()));
            }
        }
        List<LostHelpNotice> lostHelpNoticeList = lostHelpNoticeDao.queryByPage(page, params);
        return new PageInfo<>(pageIndex, pageSize, lostHelpNoticeDao.countByParams(params), lostHelpNoticeList);
    }


    public LostHelpNotice addLostHelpNotice(Map<String, Object> params) throws ParseException {
        // List<String> base64ImageList = Arrays.asList(params.get("base64ImageList").toString());
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> base64ImageList = (List<Map<String, Object>>) params.get("base64ImageList");
        String base64ImageCover = params.get("imageCover").toString();
        LostHelpNotice lostHelpNotice = new LostHelpNotice();

        try {
            lostHelpNotice.setImageCover(processBase64ToUrl(base64ImageCover));
            if (!base64ImageList.isEmpty() && base64ImageList.get(0) != null) {
                lostHelpNotice.setItemImage1(processBase64ToUrl(base64ImageList.get(0).get("base64").toString()));
            }
            if (base64ImageList.size() > 1 && base64ImageList.get(1) != null) {
                lostHelpNotice.setItemImage2(processBase64ToUrl(base64ImageList.get(1).get("base64").toString()));
            }
            if (base64ImageList.size() > 2 && base64ImageList.get(2) != null) {
                lostHelpNotice.setItemImage3(processBase64ToUrl(base64ImageList.get(2).get("base64").toString()));
            }
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            lostHelpNotice.setItemName(params.get("itemName").toString());
            lostHelpNotice.setItemDescription(params.get("itemDescription").toString());
            lostHelpNotice.setContactWay(Integer.parseInt(params.get("contactWay").toString()));
            lostHelpNotice.setLostTime(formatter.parse(params.get("lostTime").toString()));
            lostHelpNotice.setItemClassId(Integer.parseInt(params.get("itemClassId").toString()));
            lostHelpNotice.setContactNumber(params.get("contactNumber").toString());
            lostHelpNotice.setLostPositionCoordinate(params.get("lostPositionCoordinate").toString());
            lostHelpNotice.setLostPositionDescription(params.get("lostPositionDescription").toString());
            lostHelpNotice.setUserId(Integer.parseInt(params.get("userId").toString()));
            lostHelpNotice.setItemStatus(0);
            lostHelpNotice.setIfComplaint(0);
            lostHelpNotice.setIfViolation(0);
            lostHelpNotice.setIfControversy(0);
            lostHelpNoticeDao.insert(lostHelpNotice);
            // 百度智能云添加base64
//            Map<String, Object> baiduImageReq = new HashMap<>();
//            baiduImageReq.put("classId1", "1");
//            baiduImageReq.put("classId2", "3");
//            baiduImageReq.put("imageBase64", Base64Utils.removeBase64Prefix(params.get("imageCover").toString()));
//            baiduImageReq.put("imageUrl", null);
//            baiduImageReq.put("brief", lostHelpNotice.getId());
//            BaiduSimilarImageServerUtils.addImage(baiduImageReq);
        } catch (Exception e) {
            deleteAllLostHelpNoticeImage(lostHelpNotice);
            if (lostHelpNotice.getId() != null) {
                lostHelpNoticeDao.deleteById(lostHelpNotice.getId());
            }
            e.printStackTrace();
            throw new BaseException("物品生成失败");
        }
        System.out.println(lostHelpNotice.toString());
        return lostHelpNotice;
    }

    /**
     * 将base64封面图片转换为url
     *
     * @param imageBase64 base64图片
     * @return 图片url
     * @throws IOException 异常
     */
    private String processBase64ToUrl(String imageBase64) throws IOException {
        StringBuilder fileName = new StringBuilder();
        Map<String, String> imageTypeAndCode = Base64Utils.splitImageTypeAndCode(imageBase64);
        String imageType = null;
        String base64Data = null;

        if (imageTypeAndCode != null) {
            imageType = imageTypeAndCode.get("imageType");
            base64Data = imageTypeAndCode.get("base64Data");
        }

        fileName.append(System.currentTimeMillis()).append(".").append(imageType);
        // Base64转文件
        MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName.toString());
        JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");
        return (String) jsonResult.getData();
    }

    /**
     * 删除物品详情的所有图片（包括封面、详情图片）
     *
     * @param lostHelpNotice 丢失求助贴
     */
    private void deleteAllLostHelpNoticeImage(LostHelpNotice lostHelpNotice) {
        // 删除封面图片
        if (lostHelpNotice.getImageCover() != null && !lostHelpNotice.getImageCover().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(lostHelpNotice.getImageCover(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
        if (lostHelpNotice.getItemImage1() != null && !lostHelpNotice.getItemImage1().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(lostHelpNotice.getItemImage1(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
        if (lostHelpNotice.getItemImage2() != null && !lostHelpNotice.getItemImage2().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(lostHelpNotice.getItemImage2(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
        if (lostHelpNotice.getItemImage3() != null && !lostHelpNotice.getItemImage3().isEmpty()) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(lostHelpNotice.getItemImage3(),
                    "/opt/docker/apache/www/images/lost_and_found");
        }
    }
}
